package com.bjpowernode.crm.workbench.web.controller;

import com.bjpowernode.crm.commons.contants.Contants;
import com.bjpowernode.crm.commons.domain.ReturnObject;
import com.bjpowernode.crm.commons.utils.DateUtils;
import com.bjpowernode.crm.commons.utils.UUIDUtils;
import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.settings.service.UserService;
import com.bjpowernode.crm.workbench.domain.Activity;
import com.bjpowernode.crm.workbench.domain.ActivityRemark;
import com.bjpowernode.crm.workbench.service.ActivityService;
import javafx.css.StyleOrigin;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * @ClassName : ActivityController
 * @Author : 司猫子
 * @Date: 2020/12/28 16:54
 */
@Controller
public class ActivityController {
    @Autowired
    private UserService userService;
    @Autowired
    private ActivityService activityService;


    @RequestMapping("/workbench/activity/index.do")
    public String toactivity(Model model) {
        List<User> users = userService.selectAllUsers();
        model.addAttribute("userList", users);
        return "workbench/activity/index";
    }

    @RequestMapping("/workbench/activity/queryActivityForPageByCondition.do")
    @ResponseBody
    public Object queryActivityForPageByCondition(int pageNo, int pageSize, String name, String owner, String startDate, String endDate) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("beginNo", (pageNo - 1) * pageSize);
        map.put("pageSize", pageSize);
        map.put("name", name);
        map.put("owner", owner);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        List<Activity> activities = activityService.selectActivityForPageByCondition(map);
        long l = activityService.selectCountOfActivityByCondition(map);
        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("activityList", activities);
        retMap.put("totalRows", l);

        return retMap;
    }

    @RequestMapping("/workbench/activity/saveCreateActivity.do")
    @ResponseBody
    public Object saveActivity(HttpSession session, Activity activity) {
        ReturnObject returnObject = new ReturnObject();
        User user = (User) session.getAttribute(Contants.SUSSION_USER);
        activity.setId(UUIDUtils.getUUID());
        activity.setCreateTime(DateUtils.formatDateTime(new Date()));
        activity.setCreateBy(user.getId());


        int i = activityService.insertActivity(activity);
        if (i == 1) {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);

        } else {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("添加市场活动失败");
        }

        return returnObject;
    }

    @RequestMapping("/workbench/activity/deleteActivityByIds.do")
    @ResponseBody
    public Object deleteActivityByIds(String[] id) {
        ReturnObject returnObject = new ReturnObject();
        int i = activityService.deleteActivityByIds(id);
        if (i == 0) {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("删除失败,请重新操作");
        } else {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
        }
        return returnObject;
    }
    @RequestMapping("/workbench/activity/editActivity.do")
    @ResponseBody
    public Object editActivity(String id){
        Activity activity = activityService.selectActivityById(id);
        return activity;
    }

    @RequestMapping("/workbench/activity/saveEditActivity.do")
    @ResponseBody
    public Object saveEditActivity(HttpSession session, Activity activity) {
        ReturnObject returnObject = new ReturnObject();
        User user = (User) session.getAttribute(Contants.SUSSION_USER);
        activity.setEditTime(DateUtils.formatDateTime(new Date()));
        activity.setEditBy(user.getId());


        int i = activityService.updateActivity(activity);
        if (i == 1) {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);

        } else {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("添加市场活动失败");
        }

        return returnObject;
    }
    @RequestMapping("/workbench/activity/exportAllActivity.do")
    public void exportAllActivity(HttpServletRequest request, HttpServletResponse response) throws Exception{
        List<Activity> activities = activityService.selectAllActivityForDetail();
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFSheet sheet = wb.createSheet("市场活动清单");
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("市场活动id");
        cell.setCellStyle(cellStyle);
        cell = row.createCell(1);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("市场活动名称");
        cell = row.createCell(2);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("所有者");
        cell = row.createCell(3);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("开始时间");
        cell = row.createCell(4);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("结束时间");
        cell = row.createCell(5);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("成本");
        cell = row.createCell(6);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("描述");
        cell = row.createCell(7);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("创建人");
        cell = row.createCell(8);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("创建时间");
        cell = row.createCell(9);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("修改人");
        cell = row.createCell(10);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("修改时间");

        Activity activity = new Activity();
        if(activities != null){
            for (int i = 0; i < activities.size(); i++) {
                activity = activities.get(i);
                row = sheet.createRow(i+1);
                cell = row.createCell(0);
                cell.setCellValue(activity.getId());
                cell.setCellStyle(cellStyle);
                cell = row.createCell(1);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(activity.getName());
                cell = row.createCell(2);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(activity.getOwner());
                cell = row.createCell(3);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(activity.getStartDate());
                cell = row.createCell(4);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(activity.getEndDate());
                cell = row.createCell(5);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(activity.getCost());
                cell = row.createCell(6);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(activity.getDescription());
                cell = row.createCell(7);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(activity.getCreateBy());
                cell = row.createCell(8);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(activity.getCreateTime());
                cell = row.createCell(9);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(activity.getEditBy());
                cell = row.createCell(10);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(activity.getEditTime());
            }
        }
        //设置响应类型
        response.setContentType("application/octet-stream;charset=UTF-8");
        //在请求头中有一个User-Agent
        String browser = request.getHeader("User-Agent");
        //火狐ISO8859-1
        String fileName = URLEncoder.encode("市场活动列表", "UTF-8");
        if(browser.contains("firefox")){
            fileName = new String("市场活动列表".getBytes("UTF-8"),"ISO8859-1");
        }

        response.addHeader("Content-Disposition","attachment;filename="+fileName+".xls");
        //获取输出流
        OutputStream os = response.getOutputStream();
        wb.write(os);
        os.flush();
        os.close();
    }


    @RequestMapping("/workbench/activity/fileUpload.do")
    @ResponseBody
    public Object fileUpLoad(MultipartFile myFile,String username) throws Exception{
        ReturnObject returnObject = new ReturnObject();
        //以下步骤将文件上传到d://testDir
        //先获取文件名称
        String originalFilename = myFile.getOriginalFilename();
        //创建一个文件对象
        File file = new File("d:\\testDir", originalFilename);
        //将上传文件写入新建的文件
        myFile.transferTo(file);
        returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);

        return returnObject;
    }

    @RequestMapping("/workbench/activity/importActivity.do")
    @ResponseBody
    public Object importActivity(MultipartFile activityFile,String username,HttpSession session) {
        User user = (User) session.getAttribute(Contants.SUSSION_USER);
        //返回结果集
        Map<String,Object> retData = new HashMap<String, Object>();
        //解析excel文件.把每一个activity封装在一个集合中
        List<Activity> activityList = new ArrayList<Activity>();
        //获取上传的excel文件
        try {
            InputStream is = activityFile.getInputStream();
            //创建工作簿
            HSSFWorkbook wb = new HSSFWorkbook(is);
            //取第一页
            HSSFSheet sheet = wb.getSheetAt(0);
            HSSFRow row = null;
            HSSFCell cell = null;
            Activity activity = null;
            if(sheet != null){
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    row = sheet.getRow(i);
                    activity = new Activity();
                    activity.setId(UUIDUtils.getUUID());
                    activity.setCreateBy(user.getId());
                    activity.setOwner(user.getId());
                    activity.setCreateTime(DateUtils.formatDateTime(new Date()));
                    for (int j = 0; j < row.getLastCellNum(); j++) {
                        cell = row.getCell(j);
                        String cellValue = getCellValue(cell);
                        if(j == 0){
                            activity.setName(cellValue);
                        }else if(j == 1){
                            activity.setStartDate(cellValue);
                        }else if(j == 2){
                            activity.setEndDate(cellValue);
                        }else if(j == 3){
                            activity.setCost(cellValue);
                        }else if(j == 4){
                            activity.setDescription(cellValue);
                        }
                    }
                    activityList.add(activity);
                }
            }
            int i = activityService.insertActivityByList(activityList);
            if(i == 0){
                retData.put("message","文件导入失败,请稍后重试");
                retData.put("code", Contants.RETURN_OBJECT_CODE_FAIL);
            }else {
                retData.put("code",Contants.RETURN_OBJECT_CODE_SUCCESS);
                retData.put("count", i);
            }


        } catch (IOException e) {
            e.printStackTrace();
        }


        return retData;
    }

    private static String getCellValue(HSSFCell cell) {
        String ret = "";
        switch (cell.getCellType()){
            case STRING:
                ret = cell.getStringCellValue();
                break;
            case BOOLEAN:
                ret = cell.getBooleanCellValue()+"";
                break;
            default:
                ret = "";
        }
        return ret;
    }
    @RequestMapping("/workbench/clue/queryActivityForDetailByName.do")
    @ResponseBody
    public Object queryActivityForDetailByName(String activityName){

        List<Activity> activityList = activityService.selectActivityForDetailByName(activityName);

        return activityList;
    }
}
